package com.oscar.ehome.view.pageview;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.pageview.view.BannerView;
import com.oscar.ehome.view.pageview.view.baodanshujuView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/4
 * 展示网页
 */

public class BannerWebActivity extends BasesActivity<BannerView, PagePresenter> implements BannerView{
    PagePresenter pagePresenter;
    /**
     * 网页
     */
    @BindView(R.id.staticstics_webview)
    WebView staticsticsWebview;
    /**
     * 进度条
     */
    @BindView(R.id.taticstics_progressbar)
    ProgressBar taticsticsProgressbar;
    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    @BindView(R.id.quesiton_tj)
    Button quesiton_tj;
    @BindView(R.id.title_tv_right)
    TextView title_tv_right;
    String url = "";

    String type = "";//类型
    String name = "";
    String touxiang="";
    String people="";
    String  id="";
    private ShareAction shareAction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bannerweb);
        ButterKnife.bind(this);
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(BannerWebActivity.this).getSystemConfig().getColor()));
        initView();
        addView();
    }



    /**
     * 初始化
     */
    public void initView() {
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);
        //url =""
        url = getIntent().getStringExtra("contentsrc");
        type = getIntent().getStringExtra("type");
        name = getIntent().getStringExtra("name");

        switch (type) {
            case "youxi":
                titleTopbar.setText(name);
                break;
            case "yaoqing":
                titleTopbar.setText(name);
                title_tv_right.setVisibility(View.VISIBLE);
                title_tv_right.setTextSize(13);
                title_tv_right.setText("修改");
                touxiang=getIntent().getStringExtra("touxiang");
                people=getIntent().getStringExtra("people");
                Log.e("shouyessss", "initView: "+people );
                url= C.ip+C.port+getIntent().getStringExtra("contentsrc");
                quesiton_tj.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)staticsticsWebview.getLayoutParams();
                layoutParams.setMargins(0,0,0,50);//4个参数按顺序分别是左上右下
                staticsticsWebview.setLayoutParams(layoutParams);
                break;
            case "baodan":
                titleTopbar.setText(name);
                id=getIntent().getStringExtra("id");
                url= C.ip+C.port+"/app/policysheet/policySheet/loadPolicySheetAnalysis/"+id+"/1";
                Log.e("shouyessss", "initView: "+url );
                quesiton_tj.setVisibility(View.VISIBLE);
                RelativeLayout.LayoutParams layoutParamss= (RelativeLayout.LayoutParams)staticsticsWebview.getLayoutParams();
                layoutParamss.setMargins(0,0,0,160);//4个参数按顺序分别是左上右下
                staticsticsWebview.setLayoutParams(layoutParamss);
                break;
            case "hd":
                titleTopbar.setText(name);
                break;
            case "sxt":
                titleTopbar.setText(getString(R.string.sxt));
                break;
            case "zzb":
                titleTopbar.setText(getString(R.string.zzb));
                break;
            case "banner":
                titleTopbar.setText("详情");
                break;
            case "about":
                titleTopbar.setText("关于我们");
                break;
            case "server":
                titleTopbar.setText("服务协议");
                break;
            case "privacy":
                titleTopbar.setText("隐私条款");
                break;
            case "shuoming":
                titleTopbar.setText("说明文档");
                break;
        }
    }

    /**
     * 展示网页
     */
    public void addView() {
        showLoading();
        staticsticsWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//              super.onReceivedSslError(view, handler, error);
                handler.proceed();
//              handleMessage(Message msg); 其他处理
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("ceshitiaozhuan", "shouldOverrideUrlLoading: "+url );

                if (url.startsWith("http:") || url.startsWith("https:")) {
                    if(type.equals("baodan")){
                        people=url;
                    }

                    return false;
                }else if (url.startsWith("juxing://update?")){
                    String str=url.substring(16);
                    String idd=str.substring(3);
                    String splitStr;
                    int j = idd.indexOf("&");  // 找分隔符的位置
                    splitStr = idd.substring(0, j);// 找到分隔符，截取子字符串
                    str = idd.substring(splitStr.length()+15);

                    Intent intent = new Intent(BannerWebActivity.this, BaoDanNew_Activity.class);
                    intent.putExtra("baodan", str);
                    intent.putExtra("id", id);
                    intent.putExtra("xiugaiid", splitStr);
                    intent.putExtra("baodanshuliang", 0);
                    List<String> beibaoxianrenjihe =new ArrayList<String>();
                    intent.putExtra("beibaoxianrenjihe", (Serializable)beibaoxianrenjihe);
                    intent.putExtra("bianji","bianji");
                    startActivity(intent);
                    finish();
                    Log.e("ceshitiaozhuan", "shouldOverrideUrlLoading: "+splitStr+"    "+str );
                }else if(url.startsWith("juxing://delete?")){
                    String str=url.substring(16);
                    String idd=str.substring(3);
                   String token = SystemConfigFactory.getInstance(BannerWebActivity.this).getSystemConfig().getToken();
                    Log.e("ceshitiaozhuan", "shouldOverrideUrlLoading: "+idd+"    "+str );
                    pagePresenter.deletebaodan(token,idd);

                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        staticsticsWebview.setDownloadListener(new MyDownloadStart());
        // WebView加载web资源


        WebSettings webSettings = staticsticsWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings
                .setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        webSettings.setLoadWithOverviewMode(true);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        if(type.equals("yaoqing")||type.equals("baodan")){
            webSettings.setDomStorageEnabled(false);
        }else{
            webSettings.setDomStorageEnabled(true);
        }

        webSettings.setDefaultTextEncodingName("utf-8");
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(true);// 保存表单数据
        if(type.equals("yaoqing")||type.equals("baodan")){
            webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        }else{
            webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
      //关闭webview中缓存
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片


        // setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式ist.get(position);
        staticsticsWebview.setInitialScale(100);

        staticsticsWebview.setHorizontalScrollBarEnabled(false);// 水平不显示
        staticsticsWebview.setVerticalScrollBarEnabled(false); // 垂直不显示
        staticsticsWebview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        staticsticsWebview.loadUrl(url);
        staticsticsWebview.setWebChromeClient(new WebChromeClient() {

            public void onProgressChanged(WebView view, int progress) {
                taticsticsProgressbar.setProgress(progress * 100);
                if (progress == 100) {
                    dismissLoading();
                }
            }
        });
    }

    @Override
    public void deletebaodan(String map) {
        staticsticsWebview.loadUrl(people);
    }

    @Override
    public void erroy() {

    }

    @Override
    public void erry(String result) {

    }


    class MyDownloadStart implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            // TODO Auto-generated method stub
            //调用自己的下载方式
            // new HttpThread(url).start();
            //调用系统浏览器下载
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    @OnClick({R.id.title_layout_left,R.id.quesiton_tj,R.id.title_tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_tv_right:
                if(type.equals("yaoqing")){
                    Intent in=new Intent();
                    in.setClass(BannerWebActivity.this,MingPianActivity.class);
                    in.putExtra("bianji","bianji");
                    startActivity(in);
                    finish();
                }else if(type.equals("baodan")){
                    Intent in=new Intent();
                    in.setClass(BannerWebActivity.this,BaoDan_Activity.class);
                    in.putExtra("bianji","bianji");
                    in.putExtra("jiatingid",id);
                    startActivity(in);
                    finish();
                }

                break;
            case R.id.quesiton_tj:
                if(type.equals("yaoqing")){
                    openShare();
                }else if(type.equals("baodan")){
                    openSharebaodan();
                }

                break;
            case R.id.title_layout_left:
                if ((type.equals("youxi")||type.equals("banner")||type.equals("baodan"))&&staticsticsWebview.canGoBack()) {
                    staticsticsWebview.goBack();//返回上个页面
                } else if(type.equals("banner")){
                    Intent intent=new Intent();
                    intent.setClass(this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    finish();
                }

                break;
        }
    }
    /**
     * 打开分享面板
     */
    public void openShare() {
        UMImage thumb = new UMImage(BannerWebActivity.this, C.qiniu+touxiang);
        Log.e("fenxiangfanhui", "openShare: "+C.qiniu+touxiang );
        shareAction = new ShareAction(BannerWebActivity.this)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .withMedia(new UMWeb(url, "创业情，我的范儿——"+people,  "泛华是我永远的事业,泛华是你永远的朋友", thumb))
                .setCallback(umShareListener);
        shareAction.open();

    }
    public void openSharebaodan() {
        UMImage thumb = new UMImage(BannerWebActivity.this, R.mipmap.ehomelogo);
        shareAction = new ShareAction(BannerWebActivity.this)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .withMedia(new UMWeb(C.ip+C.port+"/app/policysheet/policySheet/loadPolicySheetAnalysis/"+id+"/0", "保单托管 交给泛华",  "人要体检，保单也要体检。我是泛华，您家庭的保单管家。", thumb))
                .setCallback(umShareListener);
        shareAction.open();

    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(BannerWebActivity.this, "分享成功", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t.getMessage().contains("2008")) {
                Toast.makeText(BannerWebActivity.this, "分享失败,请检查是否安装应用！", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(BannerWebActivity.this, "分享失败", Toast.LENGTH_LONG).show();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(BannerWebActivity.this, "分享取消", Toast.LENGTH_LONG).show();

        }
    };
    /**
     * 使点击回退按钮不会直接退出整个应用程序而是返回上一个页面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && staticsticsWebview.canGoBack()) {
            if ((type.equals("youxi")||type.equals("banner")||type.equals("baodan"))&&staticsticsWebview.canGoBack()) {
                staticsticsWebview.goBack();//返回上个页面
            } else if(type.equals("banner")){
                Intent intent=new Intent();
                intent.setClass(this, MainActivity.class);
                startActivity(intent);
                finish();
            }else{
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        staticsticsWebview.loadUrl("about:blank");
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

}
